<template>
  <div class="guarantee-container">
    <!-- 搜索表单 -->
    <div class="search-form">
      <el-form :model="searchForm" inline>
       
        <el-form-item label="开始时间">
          <el-date-picker
            v-model="searchForm.startTime"
            type="datetime"
            placeholder="选择开始时间"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            clearable
          />
        </el-form-item>
        <el-form-item label="结束时间">
          <el-date-picker
            v-model="searchForm.endTime"
            type="datetime"
            placeholder="选择结束时间"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            clearable
          />
        </el-form-item>
        <el-form-item label="货品批次">
          <el-input
            v-model="searchForm.batch"
            placeholder="请输入批次"
            clearable
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        
          <el-button @click="handleRefresh">刷新</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <div class="table-container">
      <el-table 
        :data="tableData" 
        style="width: 100%;" 
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="80" />
        <el-table-column prop="productCode" label="货品编号" width="120" />
        <el-table-column prop="productName" label="货品名称" min-width="180" />
        <el-table-column prop="productStatus" label="状态" width="100">
           <template #default="{ row }">
            <el-tag :type="row.productStatus === 0 ? 'success' : 'warning'">
              {{ row.productStatus === 0 ? '正常' : row.productStatus === 1 ? '到期' : '' }}
            </el-tag>
          </template>
     
        </el-table-column>
        <el-table-column prop="categoryName" label="货品类型" width="100" />
        <el-table-column prop="specifications" label="规格型号" width="120" />
        <el-table-column prop="unitName" label="单位" width="80" />
        <el-table-column prop="depotName" label="仓库名称" width="100" />
        <el-table-column prop="locationName" label="仓位名称" width="100" />
        <el-table-column prop="barcode" label="货品条码" width="120" />
        <el-table-column prop="batch" label="批次" width="100" />
        <el-table-column prop="startTime" label="生产日期" width="200" >
           <template #default="scope">
            {{ moment(scope.row.startTime).format('YYYY-MM-DD HH:mm:ss') }}
           </template>
        </el-table-column>
        <el-table-column prop="endTime" label="到期日期" width="200" >
           <template #default="scope">
            {{ moment(scope.row.endTime).format('YYYY-MM-DD HH:mm:ss') }}
           </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.PageIndex"
        v-model:page-size="pagination.PageSize"
        :total="pagination.totalCount"
        :page-sizes="[15, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import http from '@/http/axiosHelper'
import { ElMessage } from 'element-plus'
import moment from 'moment'

// 搜索表单数据
const searchForm = reactive({
  productName: '',
  categoryName: '',
  unitName: '',
  status: '',
  depotName: '',
  remainingDays: '',
  batch: '',
  barcode: '',
  startTime: '',
  endTime: ''
})

// 分页数据
const pagination = reactive({
  PageIndex: 1,
  PageSize: 15,
  totalCount: 0,
  totalPage: 0
})

// 表格数据
const tableData = ref<any[]>([])
const loading = ref(false)
const selectedRows = ref<any[]>([])


import  PurSale  from '@/http/PurSale'
// 搜索方法
const handleSearch = async () => {
  loading.value = true
  try {
    const params = {
      PageIndex: pagination.PageIndex,
      PageSize: pagination.PageSize,
      Batch: searchForm.batch,
      StartTime: searchForm.startTime,
      EndTime: searchForm.endTime,
      ProductName: searchForm.productName,
      CategoryName: searchForm.categoryName,
      UnitName: searchForm.unitName,
      Status: searchForm.status,
      DepotName: searchForm.depotName,
      RemainingDays: searchForm.remainingDays,
      Barcode: searchForm.barcode
    }
    
    try {
      const response = await http.get('/scmreadconsul/api/Ledger/ShowGuarantee', { params })
      
      if (response.data.code === 200) {
        tableData.value = response.data.items || []
        pagination.totalCount = response.data.totalCount || 0
        pagination.totalPage = response.data.totalPage || 0
        ElMessage.success('查询成功')
      } else {
        ElMessage.error(response.data.msg || '查询失败')
      }
    } catch (apiError) {
      console.error('API调用失败:', apiError)
      // 如果API调用失败，使用模拟数据
      const mockData = generateMockData()
      tableData.value = mockData
      pagination.totalCount = 100
      pagination.totalPage = 10
      ElMessage.warning('使用模拟数据，API接口暂时不可用')
    }
  } catch (error) {
    console.error('查询失败:', error)
    ElMessage.error('查询失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 生成模拟数据
const generateMockData = () => {
  const mockData = []
  const products = [
    { name: '苹果手机', code: 'HPOH6804', category: '电子产品', status: '即将到期' },
    { name: '电视机', code: 'HPOH1795', category: '家电', status: '已到期' },
    { name: '咖啡机', code: 'HPOH3705', category: '家电', status: '即将到期' },
    { name: '空调', code: 'HPOH5497', category: '家电', status: '已到期' },
    { name: '洗衣机', code: 'HPOH4568', category: '家电', status: '正常' },
    { name: '笔记本电脑', code: 'HPOH7890', category: '电子产品', status: '正常' },
    { name: '办公椅', code: 'HPOH1234', category: '家具', status: '即将到期' },
    { name: '打印机', code: 'HPOH5678', category: '电子产品', status: '正常' },
    { name: '微波炉', code: 'HPOH9012', category: '家电', status: '已到期' },
    { name: '显示器', code: 'HPOH3456', category: '电子产品', status: '正常' }
  ]
  
  const units = ['瓶', '粒', '克', '卡', '卷', '斤', '件', '盒']
  const depots = ['供应商', '客户']
  
  for (let i = 0; i < 10; i++) {
    const product = products[i % products.length]
    mockData.push({
      serialNumber: i + 1,
      productCode: product.code,
      productName: product.name,
      status: product.status,
      categoryName: product.category,
      specification: 'blue',
      unitName: units[i % units.length],
      depotName: depots[i % depots.length],
      locationName: '客户',
      barcode: `000545${i % 2 === 0 ? 'es' : 'as'}`,
      currentStock: 50,
      batch: i + 1,
      productionDate: '2025-01-22',
      expirationDate: '2025-01-25'
    })
  }
  
  return mockData
}

// 重置搜索
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    (searchForm as any)[key] = ''
  })
  pagination.PageIndex = 1
  handleSearch()
}

// 导出数据
const handleExport = () => {
  ElMessage.info('导出功能开发中...')
}

// 刷新数据
const handleRefresh = () => {
  handleSearch()
}

// 分页大小改变
const handleSizeChange = (size: number) => {
  pagination.PageSize = size
  pagination.PageIndex = 1
  handleSearch()
}

// 当前页改变
const handleCurrentChange = (page: number) => {
  pagination.PageIndex = page
  handleSearch()
}

// 选择行变化
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection
}

// 组件挂载时加载数据
onMounted(() => {
  handleSearch()
})
</script>

<style scoped>
.guarantee-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.search-form {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.table-container {
  background-color: white;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.pagination-container {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  display: flex;
  justify-content: flex-end;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.el-form-item {
  margin-bottom: 15px;
}

.el-button {
  margin-right: 10px;
}

.el-table {
  margin-top: 10px;
}

.el-tag {
  font-size: 12px;
}
</style>
